package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduChapter;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exception.MyException;
import com.mysql.cj.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author shaki
 * @since 2021-06-02
 */
@RestController
@RequestMapping("/eduservice/video")
public class EduVideoController {
    @Resource
    private EduVideoService eduVideoService;

    @Resource
    private VodClient vodClient;

    @PostMapping("/addVideo")
    public R addVideo(@RequestBody EduVideo video){
        eduVideoService.save(video);
        return R.ok();
    }

    /**
     * TODO：后面这个方法需要完善：删除小节时，同时把里面视频删除
     * @param videoId
     * @return
     */
    @DeleteMapping("{videoId}")
    public R deleteVideo(@PathVariable("videoId") String videoId){
        //根据小节id获取视频id
        EduVideo video = eduVideoService.getById(videoId);
        String videoSourceId = video.getVideoSourceId();
        if(!StringUtils.isNullOrEmpty(videoSourceId)){
            R result = vodClient.removeVideo(videoSourceId);
            if(result.getCode() == 20001){
                throw new MyException(20001,"删除视频失败，熔断器执行");
            }
        }
        eduVideoService.removeById(videoId);
        return R.ok();
    }

    @PostMapping("/updateVideo")
    public R updateVideo(@RequestBody EduVideo video){
        eduVideoService.updateById(video);
        return R.ok();
    }

    @GetMapping("/getVideoInfo/{videoId}")
    public R getVideoInfo(@PathVariable("videoId") String videoId){
        EduVideo video = eduVideoService.getById(videoId);
        return R.ok().data("video",video);
    }
}

